package com.xianyv.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xianyv.common.Result;
import com.xianyv.entity.AttendanceDetails;
import com.xianyv.service.AttendanceDetailsService;
import com.xianyv.util.ThreadLocalUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private AttendanceDetailsService detailsService;

    /**
     * 模拟签到
     * @param
     * @return
     */
    @Transactional
    @GetMapping("/sign-in")
    public Result signIn(){
        Long currentId = ThreadLocalUntil.getCurrentId();

        Instant now = Instant.now();
        long epochSecond = now.getEpochSecond() / (60*60*24);

        AttendanceDetails attendanceDetails = new AttendanceDetails();

        attendanceDetails.setId(Long.valueOf(epochSecond + currentId.toString()));
        attendanceDetails.setEmployeeId(currentId);
        attendanceDetails.setRegisterTime(LocalDateTime.now());

        boolean b = detailsService.saveOrUpdate(attendanceDetails);

        log.info("AttendanceDetails：{}",attendanceDetails);

        return b ? Result.success(attendanceDetails) : Result.error("签到失败");
    }

    /**
     * 模拟签退
     * @param employeeId
     * @return
     */
    @GetMapping("/sign-out")
    public Result signOut(Long employeeId){
        Instant now = Instant.now();
        long epochSecond = now.getEpochSecond() / (60*60*24);

        log.info("时间：{}",LocalDateTime.now());

        boolean update = detailsService.update(new LambdaUpdateWrapper<AttendanceDetails>()
                .set(AttendanceDetails::getLogoutTime, LocalDateTime.now())
                .eq(AttendanceDetails::getId, Long.valueOf(epochSecond + employeeId.toString())));
        return update ? Result.success(null) : Result.error("签退失败");
    }
}
